package com.nowcoder.mycommunity.util;

import org.apache.commons.lang3.CharUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;

import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

@Component
public class SensitiveFilter {

    private static final Logger logger = LoggerFactory.getLogger(SensitiveFilter.class);

    //替换符号
    private static final String REPLACEMENT = "***";

    //根节点
    private TrieNode rootNode = new TrieNode();

    //初始化前缀树
    @PostConstruct
    public void init(){//postConstruct注解指明在调用完类构造方法后执行的方法。项目编译完成之后所有的文件（包括资源文件）都会被加载到classes路径下，可以通过classLoader区获取这些配置文件。
        try(
                InputStream is = this.getClass().getClassLoader().getResourceAsStream("sensitive-words.txt");
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        ){
          String keyword ;
          while((keyword = reader.readLine())!=null){
              //将该敏感词添加到前缀树
              addKeyword(keyword);
          }
        }catch (IOException e){
            logger.error("加载敏感词配置文件异常！"+e.getMessage());
        }
    }

    //将一个敏感词添加到前缀树
    public void addKeyword(String keyword){
        TrieNode tempNode = rootNode;
        //遍历敏感词的每一个字符
        for (int i = 0; i < keyword.length(); i++) {
            char c = keyword.charAt(i);
            TrieNode subNode = tempNode.getSubNode(c);
            if (subNode == null){
                //初始化子节点
                subNode = new TrieNode();
                tempNode.addSubNode(c,subNode);
            }

            //指向字节点
            tempNode = subNode;

            //设置结束标识
            if (i == keyword.length() - 1){
                tempNode.setKeyWordEnd(true);
            }
        }
    }

    public String filter(String text){
        if (StringUtils.isBlank(text)) {
            return text;
        }
        //指针1
        TrieNode tempNode = rootNode;
        //指针2
        int begin = 0;
        //指针3
        int position = 0;
        //结果
        StringBuilder sb = new StringBuilder();

        while (position < text.length()){
            char c = text.charAt(position);
            if (isSymbol(c)){
                if (tempNode == rootNode){
                    sb.append(c);
                    begin ++;
                }
                //无论符号在开头还是中间，指针3都向后移动
                position ++;
                continue;
            }

            //检查下级节点
            tempNode = tempNode.getSubNode(c);
            if (tempNode == null) {
                //以begin开头的字符串不是敏感词
                sb.append(text.charAt(begin));
                //进入下一位置
                position = ++begin;
                //重新指向根节点
                tempNode = rootNode;
            }else if (tempNode.isKeyWordEnd()){
                //发现了敏感词
                sb.append(REPLACEMENT);
                begin = ++position;
                tempNode = rootNode;
            }else{
                position ++;//这里为什么不进行position越界的判断？因为如果能走到字符串的结尾，说明其之前的字符都在前缀树中出现，此时没有找到敏感词的话，说明之前的字符串均不是敏感字符。
            }
        }

        //将最后一批字符计入结果
        sb.append(text.substring(begin));
        return sb.toString();
    }

    private boolean isSymbol(Character c){
        //c< 0x2E80 || c > 0x9FFF是东亚文字
        return !CharUtils.isAsciiAlphanumeric(c) && (c< 0x2E80 || c > 0x9FFF);
    }

    //前缀树
    private class TrieNode{
        //关键词结束标记
        private boolean isKeyWordEnd = false;

        //子节点（key是下级字符，value是下级节点）
        private Map<Character,TrieNode> subNodes = new HashMap<>();

        public boolean isKeyWordEnd() {
            return isKeyWordEnd;
        }

        public void setKeyWordEnd(boolean keyWordEnd) {
            isKeyWordEnd = keyWordEnd;
        }

        //添加子节点
        public void addSubNode(Character c ,TrieNode node){
            subNodes.put(c,node);
        }

        //获取子节点
        public TrieNode getSubNode(Character c){
            return subNodes.get(c);
        }

    }
}
